<script setup lang="ts">
import { ref, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import Searchbox from "@/views/components/searchbox/Searchbox.vue";
import {
  getAlertPeopleListApi,
  deleteAlertPeopleApi,
  updateAlertPeopleStatusApi,
  AlertPeopleModel
} from "@/api/alerts/alertPeople";
import { pageSizeOptions } from "@/utils/appCommon/appCommonOptions/app";
import { useI18n } from "vue-i18n";
// 引入新增和编辑组件
import AddAlertPeople from "./component/add.vue";
import EditAlertPeople from "./component/edit.vue";
import { useLogic } from "@/views/system/user/logic/logic";
// 引入关联场景组件
import BindPeopleToScene from "@/views/alerts/scene/component/bind-people-to-scene.vue";

defineOptions({
  name: "alert-people"
});

const i18n = useI18n();
const { t } = i18n;
const pageSizeOps = ref(pageSizeOptions);

const { deptTreeList, getDeptTree } = useLogic();

onMounted(async () => {
  await getDeptTree();
});

const searchDefault = {
  name: "",
  timeRange: [],
  deptId: undefined,
  pageSize: 10,
  page: 1
};

// 搜索参数
const searchParams = ref(Object.assign({}, searchDefault));

// 搜索字段配置
const searchFields = ref([
  {
    prop: "name",
    name: t("alerts.peoplePage.search.name"),
    type: "input",
    placeholder: ""
  },
  {
    prop: "deptId",
    name: t("alerts.peoplePage.table.deptId"),
    type: "cascader",
    cascaderOptions: deptTreeList,
    ops: {
      valueField: "id",
      labelField: "name",
      emitPath: false,
      checkStrictly: true
    }
  },
  {
    prop: "timeRange",
    name: t("buttons.timeRange"),
    type: "datetimeRange",
    clearable: true,
    isHidden: false
  }
]);

// 表格数据
const tableData = ref<AlertPeopleModel[]>([]);
const total = ref(0);
const loading = ref(false);
const selectedRows = ref<AlertPeopleModel[]>([]);

// 对话框控制变量
const addDialogVisible = ref(false);
const editDialogVisible = ref(false);
const currentPeople = ref<AlertPeopleModel | null>(null);
// 关联场景对话框控制
const bindSceneDialogVisible = ref(false);
const currentBindPeople = ref<AlertPeopleModel | any>({});

// 加载数据
const loadData = async () => {
  loading.value = true;
  try {
    const params = { ...searchParams.value };
    const response = await getAlertPeopleListApi(params);
    if (response.code === 0) {
      tableData.value = response.data?.list || [];
      total.value = response.data?.total || 0;
    } else {
      ElMessage.error(response.msg || t("alerts.peoplePage.getFailed"));
    }
  } catch (error) {
    total.value = 0;
    tableData.value = [];
    ElMessage.error(t("alerts.peoplePage.getFailed"));
    console.error("Failed to load alert people list:", error);
  } finally {
    loading.value = false;
  }
};

// 初始加载
onMounted(() => {
  loadData();
});

// 分页变化处理
const handlePaginationSizeChange = (pageSize: number) => {
  searchParams.value.pageSize = pageSize;
  loadData();
};
const handlePaginationPageChange = (page: number) => {
  searchParams.value.page = page;
  loadData();
};

// 搜索处理
const handleChange = (e: any) => {
  Object.keys(e).forEach(key => {
    searchParams.value[key] = e[key];
  });
};

const handleSearch = async (e: any) => {
  searchParams.value.page = 1;
  Object.keys(e).forEach(key => {
    searchParams.value[key] = e[key];
  });
  await loadData();
};

const handleReset = (e: any) => {
  searchParams.value = Object.assign({}, searchDefault);
};

// 刷新列表
const refreshList = () => {
  loadData();
};

// 打开新增对话框
const handleAdd = () => {
  addDialogVisible.value = true;
};

// 打开编辑对话框
const handleEdit = (row: AlertPeopleModel) => {
  currentPeople.value = { ...row };
  editDialogVisible.value = true;
};

// 打开关联场景对话框
const handleBindScene = (row: AlertPeopleModel) => {
  currentBindPeople.value = row;
  bindSceneDialogVisible.value = true;
};

// 删除操作
const handleDelete = async (id: number) => {
  try {
    await ElMessageBox.confirm(
      t("alerts.peoplePage.deleteConfirm"),
      t("buttons.confirm"),
      {
        confirmButtonText: t("buttons.confirm"),
        cancelButtonText: t("buttons.cancel"),
        type: "warning"
      }
    );

    const response = await deleteAlertPeopleApi(id);
    if (response.code === 0) {
      ElMessage.success(t("alerts.peoplePage.deleteSuccess"));
      refreshList();
    } else {
      ElMessage.error(response.msg || t("alerts.peoplePage.deleteFailed"));
    }
  } catch (error: any) {
    if (error.name !== "cancel") {
      ElMessage.error(t("alerts.peoplePage.deleteFailed"));
    }
  }
};

// 批量删除
const handleSelectionChange = (rows: AlertPeopleModel[]) => {
  selectedRows.value = rows;
};

const handleBatchDelete = async () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning(t("alerts.peoplePage.selectRecordFirst"));
    return;
  }

  try {
    await ElMessageBox.confirm(
      t("alerts.peoplePage.batchDeleteConfirm", {
        count: selectedRows.value.length
      }),
      t("buttons.confirm"),
      {
        confirmButtonText: t("buttons.confirm"),
        cancelButtonText: t("buttons.cancel"),
        type: "warning"
      }
    );

    const ids = selectedRows.value.map(row => row.id);
    // 循环删除，因为接口只支持单个删除
    let allSuccess = true;
    for (const id of ids) {
      const response = await deleteAlertPeopleApi(id);
      if (response.code !== 0) {
        allSuccess = false;
        break;
      }
    }

    if (allSuccess) {
      ElMessage.success(t("alerts.peoplePage.batchDeleteSuccess"));
      await loadData();
      selectedRows.value = [];
    } else {
      ElMessage.error(t("alerts.peoplePage.batchDeleteFailed"));
    }
  } catch (error: any) {
    if (error.name !== "cancel") {
      ElMessage.error(t("alerts.peoplePage.batchDeleteFailed"));
    }
  }
};

// 格式化状态显示
const formatStatus = (status: number) => {
  return status === 1
    ? t("alerts.peoplePage.status.enabled")
    : t("alerts.peoplePage.status.disabled");
};

// 格式化语言显示
const formatLanguage = (language: string) => {
  const languageMap: Record<string, string> = {
    "zh": "中文",
    "en": "English"
  };
  return languageMap[language] || language;
};
</script>

<template>
  <el-card shadow="never">
    <template #header>
      <div class="search-area">
        <Searchbox
          :fields="searchFields"
          :initialValues="searchParams"
          :maxVisibleFields="1"
          @change="handleChange"
          @search="handleSearch"
          @reset="handleReset"
        />
      </div>
    </template>
    <div class="button-area">
      <el-button type="primary" icon="Plus" @click="handleAdd">
        {{ t("buttons.add") }}
      </el-button>
      <el-button
        type="danger"
        icon="Delete"
        @click="handleBatchDelete"
        :disabled="selectedRows.length === 0"
      >
        {{ t("buttons.batchDelete") }}
      </el-button>
    </div>

    <el-table
      :data="tableData"
      v-loading="loading"
      border
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column
        prop="name"
        :label="t('alerts.peoplePage.table.name')"
        min-width="100"
      />
      <el-table-column
        prop="deptName"
        :label="t('alerts.peoplePage.table.deptId')"
        width="120"
      />
      <el-table-column
        prop="phone"
        :label="t('alerts.peoplePage.table.phone')"
        min-width="120"
      />
      <el-table-column
        prop="email"
        :label="t('alerts.peoplePage.table.email')"
        min-width="180"
      />
      <el-table-column
        prop="language"
        :label="t('alerts.peoplePage.table.language')"
        width="100"
      >
        <template #default="{ row }">
          {{ formatLanguage(row.language) }}
        </template>
      </el-table-column>
      <el-table-column
        prop="receiveFrequency"
        :label="t('alerts.peoplePage.table.receiveFrequency')"
        width="120"
      >
        <template #default="{ row }">
          {{ row.receiveFrequency || 0 }} {{ t('time.min') }}
        </template>
      </el-table-column>
      <el-table-column
        prop="remark"
        :label="t('alerts.peoplePage.table.remark')"
        min-width="150"
      />
      <el-table-column
        prop="createdAt"
        :label="t('alerts.peoplePage.table.createdAt')"
        width="180"
      />
      <el-table-column
        :label="t('alerts.peoplePage.table.operation')"
        width="220"
      >
        <template #default="{ row }">
          <el-button type="primary" size="small" @click="handleEdit(row)">
            {{ t("buttons.edit") }}
          </el-button>
          <el-button size="small" @click="handleBindScene(row)">
            {{ t("alerts.sceneOperatePage.bindScene") }}
          </el-button>
          <el-button type="danger" size="small" @click="handleDelete(row.id)">
            {{ t("buttons.delete") }}
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      v-model:current-page="searchParams.page"
      v-model:page-size="searchParams.pageSize"
      :page-sizes="pageSizeOps"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      @size-change="handlePaginationSizeChange"
      @current-change="handlePaginationPageChange"
    />

    <!-- 新增对话框 -->
    <AddAlertPeople v-model:visible="addDialogVisible" @success="refreshList" />

    <!-- 编辑对话框 -->
    <EditAlertPeople
      v-model:visible="editDialogVisible"
      :people="currentPeople"
      @success="refreshList"
    />

    <!-- 关联场景对话框 -->
    <BindPeopleToScene
      v-model:visible="bindSceneDialogVisible"
      :people-id="currentBindPeople.id"
      :dept-id="currentBindPeople.deptId"
      @success="refreshList"
    />
  </el-card>
</template>

<style scoped lang="scss">
.card-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 16px;
}

.button-area {
  margin: 16px 0;
  display: flex;
  justify-content: flex-start;
  gap: 10px;
}

.search-area {
  margin-bottom: 16px;
}
</style>
